import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface Medicine {
  id: string
  name: string
  genericName: string
  manufacturer: string
  category: string
  type: '西药' | '中药' | '中成药' | '生物制品'
  specification: string
  unit: string
  price: number
  stock: number
  minStock: number
  maxStock: number
  batchNumber: string
  productionDate: string
  expiryDate: string
  storageCondition: string
  prescription: boolean
  status: '在售' | '停售' | '缺货' | '过期'
  barcode: string
  supplier: string
  supplierContact: string
  purchasePrice: number
  profitMargin: number
  dosageForm: string
  activeIngredient: string
  contraindication: string[]
  sideEffects: string[]
  dosage: string
  usage: string
  notes: string
  createdAt: string
  updatedAt: string
}

export interface StockTransaction {
  id: string
  medicineId: string
  medicineName: string
  type: '入库' | '出库' | '调拨' | '报损' | '盘点'
  quantity: number
  remainingStock: number
  batchNumber: string
  reason: string
  operator: string
  operatorId: string
  createdAt: string
}

export const useMedicineStore = defineStore('medicine', () => {
  const medicines = ref<Medicine[]>([
    {
      id: 'M001',
      name: '阿司匹林肠溶片',
      genericName: '乙酰水杨酸',
      manufacturer: '拜耳制药',
      category: '心血管用药',
      type: '西药',
      specification: '100mg',
      unit: '片',
      price: 0.5,
      stock: 1000,
      minStock: 100,
      maxStock: 5000,
      batchNumber: 'BN20240115',
      productionDate: '2024-01-15',
      expiryDate: '2027-01-14',
      storageCondition: '遮光、密封保存',
      prescription: false,
      status: '在售',
      barcode: '6901234567890',
      supplier: '北京医药公司',
      supplierContact: '010-12345678',
      purchasePrice: 0.3,
      profitMargin: 66.7,
      dosageForm: '肠溶片',
      activeIngredient: '乙酰水杨酸',
      contraindication: ['对阿司匹林过敏', '活动性消化道出血', '严重肝肾功能不全'],
      sideEffects: ['胃肠道反应', '出血倾向', '过敏反应'],
      dosage: '成人一次100mg，一日1次',
      usage: '口服，饭后服用',
      notes: '用于预防心血管疾病',
      createdAt: '2024-01-15T10:00:00',
      updatedAt: '2024-01-20T15:30:00'
    }
  ])

  const stockTransactions = ref<StockTransaction[]>([
    {
      id: 'T001',
      medicineId: 'M001',
      medicineName: '阿司匹林肠溶片',
      type: '入库',
      quantity: 500,
      remainingStock: 1000,
      batchNumber: 'BN20240115',
      reason: '采购入库',
      operator: '张三',
      operatorId: 'U001',
      createdAt: '2024-01-15T14:30:00'
    }
  ])

  const currentMedicine = ref<Medicine | null>(null)
  const searchQuery = ref('')
  const filterCategory = ref('')
  const filterType = ref('')
  const filterStatus = ref('')
  const loading = ref(false)

  // 获取药品列表
  const getMedicines = async (params?: any) => {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      return medicines.value
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取药品
  const getMedicineById = (id: string) => {
    return medicines.value.find(m => m.id === id)
  }

  // 添加药品
  const addMedicine = async (medicine: Omit<Medicine, 'id' | 'createdAt' | 'updatedAt'>) => {
    loading.value = true
    try {
      const newMedicine: Medicine = {
        ...medicine,
        id: `M${Date.now()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      medicines.value.unshift(newMedicine)
      return newMedicine
    } finally {
      loading.value = false
    }
  }

  // 更新药品信息
  const updateMedicine = async (id: string, updates: Partial<Medicine>) => {
    loading.value = true
    try {
      const index = medicines.value.findIndex(m => m.id === id)
      if (index > -1) {
        medicines.value[index] = { 
          ...medicines.value[index], 
          ...updates,
          updatedAt: new Date().toISOString()
        }
        return medicines.value[index]
      }
      throw new Error('药品不存在')
    } finally {
      loading.value = false
    }
  }

  // 删除药品
  const deleteMedicine = async (id: string) => {
    loading.value = true
    try {
      const index = medicines.value.findIndex(m => m.id === id)
      if (index > -1) {
        medicines.value.splice(index, 1)
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  // 搜索药品
  const searchMedicines = (query: string) => {
    searchQuery.value = query
    if (!query) return medicines.value
    
    return medicines.value.filter(medicine => 
      medicine.name.includes(query) ||
      medicine.genericName.includes(query) ||
      medicine.manufacturer.includes(query) ||
      medicine.category.includes(query)
    )
  }

  // 按分类筛选
  const filterMedicinesByCategory = (category: string) => {
    filterCategory.value = category
    if (!category) return medicines.value
    
    return medicines.value.filter(medicine => medicine.category === category)
  }

  // 按类型筛选
  const filterMedicinesByType = (type: string) => {
    filterType.value = type
    if (!type) return medicines.value
    
    return medicines.value.filter(medicine => medicine.type === type)
  }

  // 按状态筛选
  const filterMedicinesByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return medicines.value
    
    return medicines.value.filter(medicine => medicine.status === status)
  }

  // 获取库存不足的药品
  const getLowStockMedicines = () => {
    return medicines.value.filter(medicine => medicine.stock <= medicine.minStock)
  }

  // 获取即将过期的药品
  const getExpiringMedicines = (days: number = 30) => {
    const targetDate = new Date()
    targetDate.setDate(targetDate.getDate() + days)
    
    return medicines.value.filter(medicine => {
      const expiryDate = new Date(medicine.expiryDate)
      return expiryDate <= targetDate && expiryDate > new Date()
    })
  }

  // 库存操作
  const updateStock = async (
    medicineId: string, 
    type: StockTransaction['type'], 
    quantity: number, 
    reason: string,
    operator: string,
    operatorId: string,
    batchNumber?: string
  ) => {
    loading.value = true
    try {
      const medicine = medicines.value.find(m => m.id === medicineId)
      if (!medicine) throw new Error('药品不存在')

      let newStock = medicine.stock
      if (type === '入库' || type === '调拨') {
        newStock += quantity
      } else if (type === '出库' || type === '报损') {
        if (quantity > medicine.stock) {
          throw new Error('库存不足')
        }
        newStock -= quantity
      } else if (type === '盘点') {
        newStock = quantity
      }

      // 更新库存
      medicine.stock = newStock
      medicine.updatedAt = new Date().toISOString()

      // 检查库存状态
      if (newStock <= 0) {
        medicine.status = '缺货'
      } else if (medicine.status === '缺货' && newStock > 0) {
        medicine.status = '在售'
      }

      // 记录库存变动
      const transaction: StockTransaction = {
        id: `T${Date.now()}`,
        medicineId,
        medicineName: medicine.name,
        type,
        quantity,
        remainingStock: newStock,
        batchNumber: batchNumber || medicine.batchNumber,
        reason,
        operator,
        operatorId,
        createdAt: new Date().toISOString()
      }
      
      stockTransactions.value.unshift(transaction)
      return transaction
    } finally {
      loading.value = false
    }
  }

  // 获取库存变动记录
  const getStockTransactions = (medicineId?: string) => {
    if (medicineId) {
      return stockTransactions.value.filter(t => t.medicineId === medicineId)
    }
    return stockTransactions.value
  }

  // 批量导入药品
  const batchImportMedicines = async (medicineData: Partial<Medicine>[]) => {
    loading.value = true
    try {
      const newMedicines: Medicine[] = []
      
      for (const data of medicineData) {
        const medicine: Medicine = {
          id: `M${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          name: data.name || '',
          genericName: data.genericName || '',
          manufacturer: data.manufacturer || '',
          category: data.category || '',
          type: data.type || '西药',
          specification: data.specification || '',
          unit: data.unit || '',
          price: data.price || 0,
          stock: data.stock || 0,
          minStock: data.minStock || 0,
          maxStock: data.maxStock || 0,
          batchNumber: data.batchNumber || '',
          productionDate: data.productionDate || '',
          expiryDate: data.expiryDate || '',
          storageCondition: data.storageCondition || '',
          prescription: data.prescription || false,
          status: data.status || '在售',
          barcode: data.barcode || '',
          supplier: data.supplier || '',
          supplierContact: data.supplierContact || '',
          purchasePrice: data.purchasePrice || 0,
          profitMargin: data.profitMargin || 0,
          dosageForm: data.dosageForm || '',
          activeIngredient: data.activeIngredient || '',
          contraindication: data.contraindication || [],
          sideEffects: data.sideEffects || [],
          dosage: data.dosage || '',
          usage: data.usage || '',
          notes: data.notes || '',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        }
        
        newMedicines.push(medicine)
      }
      
      medicines.value.unshift(...newMedicines)
      return newMedicines
    } finally {
      loading.value = false
    }
  }

  // 计算利润率
  const calculateProfitMargin = (price: number, purchasePrice: number) => {
    if (purchasePrice === 0) return 0
    return Math.round(((price - purchasePrice) / purchasePrice) * 100 * 100) / 100
  }

  // 检查药品是否过期
  const isExpired = (expiryDate: string) => {
    return new Date(expiryDate) < new Date()
  }

  // 获取统计数据
  const getMedicineStats = () => {
    const total = medicines.value.length
    const lowStock = getLowStockMedicines().length
    const expiring = getExpiringMedicines().length
    const expired = medicines.value.filter(m => isExpired(m.expiryDate)).length
    
    const byCategory = medicines.value.reduce((acc, medicine) => {
      acc[medicine.category] = (acc[medicine.category] || 0) + 1
      return acc
    }, {} as Record<string, number>)
    
    const byType = medicines.value.reduce((acc, medicine) => {
      acc[medicine.type] = (acc[medicine.type] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const byStatus = medicines.value.reduce((acc, medicine) => {
      acc[medicine.status] = (acc[medicine.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const totalValue = medicines.value.reduce((sum, medicine) => {
      return sum + (medicine.price * medicine.stock)
    }, 0)

    const totalCost = medicines.value.reduce((sum, medicine) => {
      return sum + (medicine.purchasePrice * medicine.stock)
    }, 0)

    return {
      total,
      lowStock,
      expiring,
      expired,
      byCategory,
      byType,
      byStatus,
      totalValue,
      totalCost,
      totalProfit: totalValue - totalCost
    }
  }

  return {
    medicines,
    stockTransactions,
    currentMedicine,
    searchQuery,
    filterCategory,
    filterType,
    filterStatus,
    loading,
    getMedicines,
    getMedicineById,
    addMedicine,
    updateMedicine,
    deleteMedicine,
    searchMedicines,
    filterMedicinesByCategory,
    filterMedicinesByType,
    filterMedicinesByStatus,
    getLowStockMedicines,
    getExpiringMedicines,
    updateStock,
    getStockTransactions,
    batchImportMedicines,
    calculateProfitMargin,
    isExpired,
    getMedicineStats
  }
}, {
  persist: {
    key: 'medicine-store',
    storage: localStorage,
    paths: ['medicines', 'stockTransactions']
  }
})